package lv.rtu.ditf.dc.stream;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

/**
 * 
 * @author Pāvels Koliškins, Edgars Matisāns
 *
 */
public class StringStreamWriter {
	public static void write(String content, OutputStream outStream, String encoding) throws IOException {
		Writer writer = null;
		if (encoding != null)
			try {
				writer = new OutputStreamWriter(outStream, encoding);
			}
			catch (UnsupportedEncodingException ex) {
				// TODO log
				ex.printStackTrace();
			}
		
		if (writer == null)
			writer = new OutputStreamWriter(outStream);

		BufferedWriter buffWriter = null;
        try {
            buffWriter = new BufferedWriter(writer);
            buffWriter.write(content);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (buffWriter != null) {
                try {
                    buffWriter.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }	
	}
}
